<template>
  <el-card>
    <template #header>商品添加</template>

    <!-- 表单布局 -->
    <el-form
      :model="goodsForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
      size="mini"
    >
      <!-- 输入框 -->
      <el-form-item label="商品名称" prop="goodsName">
        <el-input v-model="goodsForm.goodsName"></el-input>
      </el-form-item>
      <!-- 下拉框 -->
      <el-form-item label="商品分类" prop="goodsCate">
        <el-select v-model="goodsForm.goodsCate" placeholder="请选择活动区域">
          <el-option
            v-for="item in cateArr"
            :key="item.cateName"
            :label="item.cateName"
            :value="item.cateName"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 步进器 -->
      <el-form-item label="商品价格">
        <el-input-number
          v-model="goodsForm.price"
          :min="1"
          :max="10"
          label="描述文字"
        ></el-input-number>
      </el-form-item>

      <!-- 图片上传 -->
      <el-form-item label="商品图片">
        <el-upload
          class="avatar-uploader"
          action="http://127.0.0.1:5000/goods/goods_img_upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <!-- 文本域 -->
      <el-form-item label="商品描述" prop="desc">
        <el-input type="textarea" v-model="goodsForm.desc"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >添加商品</el-button
        >
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { getAllCates, addGoods } from '@/api/goods.js'

export default {
  data() {
    return {
      cateArr: [],
      imageUrl: '',
      // 数据对象
      goodsForm: {
        goodsName: '',
        goodsCate: '',
        price: '',
        imgUrl: '',
        desc: ''
      },
      // 规则对象
      rules: {
        goodsName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        goodsCate: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ],
        desc: [{ required: true, message: '请输入商品名称', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getCates()
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          // 验证一下商品图片
          if (this.goodsForm.imgUrl === '') {
            return this.$message.error('请上传图片！！')
          }
          // 代表所有的数据校验通过了，可以发请求了
          const { goodsName, goodsCate, price, imgUrl, desc } = this.goodsForm
          const { code } = await addGoods({
            name: goodsName,
            category: goodsCate,
            price,
            imgUrl,
            goodsDesc: desc
          })
          if (code === 0) {
            setTimeout(() => {
              this.$router.push('/goods/list')
            }, 1500)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    async getCates() {
      const { categories } = await getAllCates()
      // console.log(data)
      this.cateArr = categories
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      // console.log(res)
      this.goodsForm.imgUrl = res.imgUrl
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const arr = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif']
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!arr.includes(file.type)) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return arr.includes(file.type) && isLt2M
    }
  }
}
</script>

<style lang="less" scoped>
.el-input {
  width: 178px;
}

/deep/textarea {
  width: 400px;
  height: 80px;
  resize: none;
}

/deep/.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
/deep/.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  line-height: 128px;
  text-align: center;
}
.avatar {
  width: 128px;
  height: 128px;
  display: block;
}
</style>
